﻿using Aliyun.OSS;
using Microsoft.Extensions.Configuration;

namespace KAs.Utils.Oss;

public class AliyunOssService : IAliyunOssService
{
    private readonly string _bucketName;
    private readonly OssClient _client;

    public AliyunOssService(IConfiguration configuration)
    {
        var aliOssConfig = configuration.GetSection("Oss:Aliyun").Get<AliyunOssConfig>();
        if (aliOssConfig == null)
            throw new Exception("aliyun oss config error.");
        _bucketName = aliOssConfig.BucketName;
        _client = new OssClient(aliOssConfig.EndPoint, aliOssConfig.AccessKeyId, aliOssConfig.AccessKeySecret);
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="inputStream"></param>
    /// <param name="savePath"></param>
    /// <exception cref="Exception"></exception>
    public void UploadFile(Stream inputStream, string savePath)
    {
        try
        {
            _client.PutObject(_bucketName, savePath, inputStream);
        }
        catch (Exception ex)
        {
            throw new Exception("aliyun oss upload failed," + ex.Message);
        }
    }

    /// <summary>
    /// 生成临时访问的路径
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public string GenerateUrl(string fileName, int minutes = 30)
    {
        if (string.IsNullOrEmpty(fileName)) return string.Empty;

        try
        {
            var req = new GeneratePresignedUriRequest(_bucketName, fileName)
            {
                Expiration = DateTime.Now.AddMinutes(minutes),
                ResponseHeaders = new ResponseHeaderOverrides
                {
                    ContentDisposition = "inline"
                }
            };
            var uri = _client.GeneratePresignedUri(req);
            var urlStr = uri.ToString();
            return urlStr;
        }
        catch
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="fileName"></param>
    /// <exception cref="Exception"></exception>
    public void DeleteFile(string fileName)
    {
        try
        {
            _client.DeleteObject(new DeleteObjectRequest(_bucketName, fileName));
        }
        catch (Exception ex)
        {
            throw new Exception("aliyun oss delete failed," + ex.Message);
        }
    }
}
